package com.ruoyi.qualityControl.utils;


import com.google.gson.JsonObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class OBSWebSocketClientTest {
    private static final String OBS_WEBSOCKET_ADDR = "localhost";
    private static final int OBS_WEBSOCKET_PORT = 4455; // 默认端口是4444，可能需要根据实际情况修改
    private static final String PASSWORD = "213"; // 设置时OBS WebSocket插件中设置的密码

    public static void main(String[] args) {
        try {
            Socket socket = new Socket(OBS_WEBSOCKET_ADDR, OBS_WEBSOCKET_PORT);
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

            // 连接OBS WebSocket
            JsonObject auth = new JsonObject();
            auth.addProperty("request-type", "GetAuthRequired");
            String authStr = auth.toString();
            sendMessage(dos, authStr);

            // 验证密码
            auth = new JsonObject();
            auth.addProperty("request-type", "Authenticate");
            auth.addProperty("auth", PASSWORD);
            String authResponseStr = auth.toString();
            sendMessage(dos, authResponseStr);

            // 开始录制
            JsonObject startRecording = new JsonObject();
            startRecording.addProperty("request-type", "StartRecording");
            String startRecordingStr = startRecording.toString();
            sendMessage(dos, startRecordingStr);

            socket.close();
        } catch (IOException e) {
            System.out.println("异常"+e);
            e.printStackTrace();
        }
    }

    private static void sendMessage(DataOutputStream dos, String message) throws IOException {
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        dos.writeInt(bytes.length);
        dos.write(bytes);
        dos.flush();

        System.out.println("Message sent: " + message);
    }

    private static String receiveMessage(InputStream is) throws IOException {
        int messageLength = is.read();
        if (messageLength == 0) {
            return null;
        }

        byte[] bytes = new byte[messageLength];
        is.read(bytes);

        String message = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("Message received: " + message);

        return message;
    }
}